package com.example.sherlockzhong.plush_v2.Subscriptions;

/*
 * Created by DosonLeung on 2014/8/28.
 */

import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Display;
import android.view.View;
import android.view.animation.AnimationSet;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.example.sherlockzhong.plush_v2.CardBeans.ScheduleBean;
import com.example.sherlockzhong.plush_v2.CardIni.ScheduleIni;
import com.example.sherlockzhong.plush_v2.Components.buttons.BackButton;
import com.example.sherlockzhong.plush_v2.Models.ClassesModel;
import com.example.sherlockzhong.plush_v2.R;
import com.example.sherlockzhong.plush_v2.View.ScheduleHorizontalScrollFullView;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Calendar;

public class ScheduleActivity extends Activity {

    ScheduleBean schedulebeans[] = new ScheduleBean[]{new ScheduleBean(), new ScheduleBean(), new ScheduleBean(), new ScheduleBean(), new ScheduleBean(), new ScheduleBean(), new ScheduleBean()};
    JSONArray jsonArray;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            stopReflashDialog();
            if (msg.what == 0x200) {
                try {
                    getLessonCardListView(jsonArray);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (msg.what == 0x201) {
                if (jsonArray != null && jsonArray.length() > 0) {
                    try {
                        getLessonCardListView(jsonArray);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    Toast.makeText(ScheduleActivity.this, "刷新成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(ScheduleActivity.this, "网络超时,请检查您的网络设置。", Toast.LENGTH_SHORT).show();
                }
            }
        }
    };
    Thread refresh = new Thread() {
        @Override
        public void run() {
            ClassesModel.saveClasses(ClassesModel.getClasses());
            jsonArray = ClassesModel.findAll();
            handler.sendEmptyMessage(0x200);
        }
    };
    private Activity self = this;
    private boolean isRefreshing = false;
    private Thread refreshThread = null;
    private ProgressDialog pd;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.schedule_full);
        initWidget();
        try {
            jsonArray = ClassesModel.findAll();
            getLessonCardListView(jsonArray);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    public void getLessonCardListView(JSONArray jsonArrays) throws JSONException {
        if (jsonArrays == null) {
            return;
        }
        String contents[] = new String[6];
        String addresses[] = new String[6];
        String teachers[] = new String[6];
        String weeks[] = new String[6];
        String headers[] = new String[6];
        try {
            for (int i = 0; i < 7; i++) {
                JSONArray jsonArray = jsonArrays.getJSONArray(i);
                for (int j = 0; j < 6; j++) {
                    JSONObject jsonClass = jsonArray.getJSONObject(j);
                    if (jsonClass != null) {
                        if (jsonClass.getString("class_name").equals("empty")) {
                            contents[j] = "";
                            addresses[j] = "";
                            teachers[j] = "";
                            weeks[j] = "";
                            headers[j] = "";
                        } else {
                            contents[j] = jsonClass.getString("class_name");
                            addresses[j] = jsonClass.getString("class_room");
                            teachers[j] = jsonClass.getString("teacher_name");
                            weeks[j] = jsonClass.getString("weeks_sumary");
                            headers[j] = jsonClass.getString("class_order");
                        }
                    } else {
                        contents[j] = "";
                        addresses[j] = "";
                        teachers[j] = "";
                        weeks[j] = "";
                        headers[j] = "";
                    }
                }
                schedulebeans[i].setContents(contents);
                schedulebeans[i].setAddresses(addresses);
                schedulebeans[i].setTeacher(teachers);
                schedulebeans[i].setWeek(weeks);
                schedulebeans[i].setHeaders(headers);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        ScheduleIni.generateList(this, (ListView) findViewById(R.id.monday_list), schedulebeans[0].generateScheduleListData());
        ScheduleIni.generateList(this, (ListView) findViewById(R.id.tuesday_list), schedulebeans[1].generateScheduleListData());
        ScheduleIni.generateList(this, (ListView) findViewById(R.id.wednesday_list), schedulebeans[2].generateScheduleListData());
        ScheduleIni.generateList(this, (ListView) findViewById(R.id.thursday_list), schedulebeans[3].generateScheduleListData());
        ScheduleIni.generateList(this, (ListView) findViewById(R.id.friday_list), schedulebeans[4].generateScheduleListData());
        ScheduleIni.generateList(this, (ListView) findViewById(R.id.saturday_list), schedulebeans[5].generateScheduleListData());
        ScheduleIni.generateList(this, (ListView) findViewById(R.id.sunday_list), schedulebeans[6].generateScheduleListData());

        Display display = getWindowManager().getDefaultDisplay();
        Point p = new Point();
        display.getSize(p);
        final int windowWidth = p.x;
        ScheduleHorizontalScrollFullView schedulefull_inside = (ScheduleHorizontalScrollFullView) findViewById(R.id.schedulefull_inside);
        schedulefull_inside.setApp(this);
        ScheduleIni.shapeScheduleHorizontalScrollViewFull(this, schedulefull_inside);
        schedulefull_inside.setScrollDistance(windowWidth);
        int today = Calendar.getInstance().get(Calendar.DAY_OF_WEEK) - 1;
        if (today == 0) {
            schedulefull_inside.initTo(6);
        } else {
            schedulefull_inside.initTo(today - 1);
        }
    }

    private void initWidget() {
        ((BackButton) findViewById(R.id.schedule_back)).setApp(this);
        final ImageView refreshButton = (ImageView) findViewById(R.id.schedule_refresh);
        refreshButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AnimationSet as = new AnimationSet(true);
                final float w = refreshButton.getWidth() / 2;
                final float h = refreshButton.getHeight() / 2;
                RotateAnimation ra = new RotateAnimation(0, 720, w, h);
                ra.setDuration(500);
                as.addAnimation(ra);
                refreshButton.startAnimation(as);
                showReflashDialog("加载中...");
                jsonArray = null;
                new Thread() {
                    @Override
                    public void run() {
                        ClassesModel.saveClasses((ClassesModel.getClasses()));
                        jsonArray = ClassesModel.findAll();
                        handler.sendEmptyMessage(0x201);
                    }
                }.start();
            }
        });
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    /**
     * 显示刷新的时候的等待进度条
     */
    private void showReflashDialog(String msg) {
        this.pd = new ProgressDialog(this);
        this.pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        this.pd.setCancelable(false);
        this.pd.setMessage(msg);
        this.pd.show();
    }

    /**
     * 结束刷新的时候的等待进度条
     */
    private void stopReflashDialog() {
        if (this.pd != null) {
            pd.dismiss();
        }
    }

    public void onDestory() {
        super.onDestroy();
        stopReflashDialog();
    }
}
